package com.ucar.common.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.ucar.common.properties.swagger.SwaggerApiInfo;
import com.ucar.common.properties.swagger.SwaggerProperties;

import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
/**
 * 整合swagger
 * @author dinghao
 *
 */
@Configuration
@EnableConfigurationProperties(SwaggerProperties.class)
@EnableSwagger2
public class SwaggerConfig {
	// 日志
	private final Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	private SwaggerProperties swaggerProperties;

	@Bean
	public Docket docket() {

		Docket docket;
		if (null == swaggerProperties.getApiInfo() || null == swaggerProperties.getBasePackage()) {
			docket = new Docket(DocumentationType.SWAGGER_2);
			logger.info("没有配置swagger");
		} else {
			docket = new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo(swaggerProperties.getApiInfo())).select()
					.apis(RequestHandlerSelectors.basePackage(swaggerProperties.getBasePackage())).build();
			logger.info("成功实例化swagger：Docket");
			logger.info("yml文件swagger配置如下\n{}","swagger:\r\n" + 
					"  api-info:\r\n" + 
					"    contact: 小逗比\r\n" + 
					"    description: 小工具\r\n" + 
					"    email: 754124441@qq.com\r\n" + 
					"    title: 小工具\r\n" + 
					"    url: www.example.com\r\n" + 
					"    version: 1.0\r\n" + 
					"  basePackage: com.ucar.test.controller");
		}
		return docket;
	}

	private ApiInfo apiInfo(SwaggerApiInfo swaggerApiInfo) {
		ApiInfo apiInfo = new ApiInfoBuilder().title(swaggerApiInfo.getTitle()).description(swaggerApiInfo.getDescription())
				.contact(new Contact(swaggerApiInfo.getContact(), swaggerApiInfo.getUrl(), swaggerApiInfo.getEmail()))
				.version(swaggerApiInfo.getVersion()).build();
		return apiInfo;
	}
}
